<?php
namespace app\admin\controller;

use app\admin\service\LoginService;
use app\BaseController;
use app\libs\exception\ClientTypeError;
use app\libs\exception\ParamException;
use app\libs\exception\ServerError;
use app\libs\tool\CacheTool;
use app\model\AdminUser;

class Admin extends BaseController
{
    /**
     * @throws ServerError
     * @throws ParamException
     * @throws ClientTypeError
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function login()
    {
        // 接收参数
        $param = $this->request->param(['account', 'password', 'captcha']);

        // 验证参数
        $this->verifyParam($param, "AdminValidate.login");

        //获取数据
        $data = AdminUser::field('id, salt, password')
            ->where('account', $param['account'])
            ->find();

        if (!$data) {
            throw new ClientTypeError(['message' => '您输入的账号不存在']);
        }

        //判断密码是否一致
        if (!$data->check_pwd($param['password'])) {
            throw new ClientTypeError(['message' => '请输入正确的账号或密码']);
        }

        //获取jwt
        $jwt = (new LoginService())->save_return_jwt($data->id);

        return json([
            'token' => $jwt,
        ]);
    }

    public function userInfo()
    {
        // 当前用户id
        $id = CacheTool::getCurrentUserId();
        return json($id);
    }
}